package com.jubaozan.c3.framework.logs.logback;

import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.boolex.EventEvaluatorBase;
import lombok.RequiredArgsConstructor;

import lombok.extern.slf4j.Slf4j;
import org.codehaus.janino.ExpressionEvaluator;

/**
 * @author jiangjinwu
 * @version 1.0
 * @since 2025/10/8 10:48
 */

@Slf4j

public class ExpressionLogEvaluator extends EventEvaluatorBase<ILoggingEvent> {
  // 表达式字符串，会从 logback-spring.xml 读取
  private String expression;

  private ExpressionEvaluator evaluator;

  @Override
  public void start() {
    if (expression == null || expression.trim().isEmpty()) {
      addError("expression 未配置");
      return;
    }
    try {
      // 告诉 Janino 表达式的返回类型是 boolean
      evaluator = new ExpressionEvaluator(
          expression,
          boolean.class,
          new String[]{"event"}, // 表达式里可用的变量名
          new Class[]{ILoggingEvent.class} // 变量类型
      );
      super.start();
    } catch (Exception e) {
      addError("表达式编译失败: " + expression, e);
    }
  }

  @Override
  public boolean evaluate(ILoggingEvent event) {
    if (!isStarted()) {
      return false;
    }
    try {
      // 执行表达式，传入 event 变量
      Object result = evaluator.evaluate(new Object[]{event});
      return Boolean.TRUE.equals(result);
    } catch (Exception e) {
      addError("表达式执行失败: " + expression, e);
      return false;
    }
  }

  // 让 logback 可以通过 XML 设置 expression
  public void setExpression(String expression) {
    this.expression = expression;
  }
}
